import requests
import json


# 流式输出的响应！！！！
#
#
#

url = "https://api.siliconflow.cn/v1/chat/completions"

payload = {
    "model": "internlm/internlm2_5-7b-chat",
    "stream": True,  # 启用流式输出
    "max_tokens": 512,
    "temperature": 0.01,
    "top_p": 0.01,
    "top_k": 1,
    "frequency_penalty": 0,
    "n": 1,
    "stop": [],
    "messages": [
        {
            "content": "你好，你是谁？",
            "role": "user"
        }
    ]
}


headers = {
    "Authorization": "Bearer sk-pusgnznrckhdogxrchddbfzrypvljzjdydjogvnfbprehtkj",
    "Content-Type": "application/json"
}

# 发送请求并获取流式响应
response = requests.post(url, json=payload, headers=headers, stream=True)
response.encoding = "utf-8"

# 逐行读取流式响应
for line in response.iter_lines(decode_unicode=True):
    if line and line.startswith("data: "):  # 去掉 data: 前缀
        line = line[6:].strip()  # 提取实际 JSON 数据
        try:
            data = json.loads(line)  # 解析 JSON 数据
            # 提取生成的内容字段
            if "choices" in data and len(data["choices"]) > 0:
                content = data["choices"][0].get("delta", {}).get("content", "")
                if content:
                    print(content, end="", flush=True)  # 实时输出到终端
        except json.JSONDecodeError as e:
            print(f"\nFailed to parse JSON: {line}")